let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');
let partials = require('express-partials');

let env = require('./utils/env');
// router
let index = require('./routes/index');
let user = require('./routes/user');
let component = require('./routes/component');
let appRouter = require('./routes/app');
let package = require('./routes/package');
let ueditor = require('./routes/ueditor');
let qrcode = require('./routes/qrcode');
let admin = require('./routes/admin');
let api = require('./routes/api');
let help = require('./routes/help');
let guanjia = require('./routes/guanjia');
let script = require('./routes/script');

let Applications = require('./models/Applications');
let Packages = require('./models/Packages');
// support
var session = require('express-session');
var socketServer = require('./utils/socket');
var website = require('./utils/website');
var db = require('./db');

// model
var Users = require('./models/Users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(partials());


app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({resave: true,saveUninitialized: true, secret: 'leopard', cookie: { maxAge: 1000 * 3600 * 24 }}))
app.use(express.static(path.join(__dirname, 'public')));
app.use('/data',express.static(path.join(__dirname, 'data')));

app.use(require('flash')());


db.connect(function (err) {
    if (err) {
        console.log('连接数据库出现问题:'+err)
    }
    console.log(website.webname() + '已启动');
    require('./utils/init')();
});

process.on('unhandledRejection', (reason, p) => {

});

app.use(function (req,res,next) {
    res.locals.website = website;
    res.locals.baseUrl = website.url(req);
    next();
});

app.use(function(req,res,next){
    function goNext() {
        var flash = res.locals.flash;
        if (flash.length > 0) {
            var info = flash[0];
            var type = info['type'];
            var message = info['message'];
            if (type === 'success') {
                res.locals.error = null;
                res.locals.success = message;
            } else {
                res.locals.error = message;
                res.locals.success = null;
            }
            req.session.flash = [];
        } else {
            res.locals.error = null;
            res.locals.success = null;
        }
        next();
    }
    res.locals.user = null;
    if (req.session.uid) {
        Users.getbyId(req.session.uid,function (err,user) {
            res.locals.user=user;
            goNext();
        });
    } else  {
        res.locals.user=null;
        goNext();
    }

});

app.use(function (req,res,next) {
    if (req.session.socketServer == null) {
        req.session.socketServer = socketServer;
    }
    next();
});

app.use('/', index);
app.use('/ueditor',ueditor);
app.use('/package',package);
app.use('/user', user);
app.use('/app',appRouter);
app.use('/script',script);
app.use('/component',component);
app.use('/admin',admin);
app.use('/guanjia',guanjia);
app.use('/qrcode',qrcode);
app.use('/api',api);
app.use('/help',help);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    if (env.isDevelop()) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    } else {
        res.status(404);
        res.render("404",{title:"走丢了"});
    }

});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = err;
  res.locals.title = '出错啦';
  res.locals.success = null;
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


module.exports = app;
